package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketBrand;
import com.cskaoyan.market.service.MarketBrandService;
import com.cskaoyan.market.service.impl.MarketBrandServiceImpl;
import com.cskaoyan.market.util.HttpUtil;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@WebServlet("/admin/brand/*")
public class AdminBrandController extends HttpServlet {
    private MarketBrandService brandService = new MarketBrandServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/brand/", "");
        if ("list".equals(op)) {
            list(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/brand/", "");
        if ("create".equals(op)) {
            create(req, resp);
        } else if ("update".equals(op)) {
            update(req, resp);
        } else if ("delete".equals(op)) {
            delete(req, resp);
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String name = req.getParameter("name");
        String idParam = req.getParameter("id");
        //对请求参数进行校验
        //pageParam和limit为必要参数，需要判断是否为空
        if (StringUtils.isEmpty(pageParam) || StringUtils.isEmpty(limitParam)) {
                resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
        }
        //sort和order如果为空，则设置一个默认值
        if (sort == null) {
            sort = "add_time";
        }
        if (order == null) {
            order = "desc";
        }

        int id=0;
        int page;
        int limit;

        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
            if (!StringUtils.isEmpty(idParam)) {
                id = Integer.parseInt(idParam);
            }
        } catch (NumberFormatException e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }

        List<MarketBrand> marketList = brandService.list(page, limit, sort, order, id, name);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(marketList)));

    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        MarketBrand brand = new MarketBrand();
        try {
            brand = JacksonUtil.getObjectMapper().readValue(requestBody, MarketBrand.class);
        } catch (Exception e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
        }
        LocalDateTime now = LocalDateTime.now();
        brand.setAddTime(now);
        brand.setUpdateTime(now);
        int result = brandService.create(brand);
        String resultString;
        if (result == 1) {
            resultString = JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(brand));
        } else {
            resultString = JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.fail(-1, "品牌商添加失败"));
        }
        resp.getWriter().println(resultString);
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        MarketBrand brand = new MarketBrand();
        try {
            brand = JacksonUtil.getObjectMapper().readValue(requestBody, MarketBrand.class);
        } catch (Exception e) {
            resp.getWriter().println(ResponseUtil.badArgument());
        }
        brand.setUpdateTime(LocalDateTime.now());
        int result = brandService.update(brand);
        String resultString;
        if (result == 1) {
            resultString = JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok());
        } else {
            resultString = JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.fail(-1, "品牌修改失败"));
        }
        resp.getWriter().println(resultString);
    }


    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        MarketBrand brand = null;
        try {
            brand = JacksonUtil.getObjectMapper().readValue(requestBody, MarketBrand.class);
        } catch (Exception e) {
            resp.getWriter().println(ResponseUtil.badArgument());
        }
        brand.setUpdateTime(LocalDateTime.now());
        //进行逻辑删除
        brand.setDeleted(true);
        int result = brandService.update(brand);
        String resultString;
        if (result == 1) {
            resultString = JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok());
        } else {
            resultString = JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.fail(-1, "品牌删除失败"));
        }
        resp.getWriter().println(resultString);
    }
}
